import React, { useEffect, useLayoutEffect, useState } from 'react';
import './index.scss';
import Button from '../../components/Button';
import Layout from '../../components/Layout';
import Popup from '../../components/Popup';
import CustomerAdd from './add';
import { sessionGet } from '../../utils/storage';
import { ApiCustomerList } from '../../api/customer';
import { CustomerListType } from './type';
import Emitter from '../../utils/events';
import { ResType } from '../../types/response';
import { useNavigate } from 'react-router-dom';
import Pagination from '../../components/Pagination';

function Customer() {
  const navigate = useNavigate();
  let employeeId = sessionGet('YH_CUSTOMER_ID');
  const [popupShow, setPopupShow] = useState<Boolean>(false);
  const [info, setInfo] = useState<CustomerListType>({
    employee_id: employeeId || '',
    page: 1,
    pageSize: 2,
  });
  const [list, setList] = useState<any[]>([]);
  const [total, setTotal] = useState<number>(0);

  // 改变弹出框状态
  const popupFunction = () => {
    setPopupShow(!popupShow);
  };

  // 初始化
  useLayoutEffect(() => {
    if (!info.employee_id) {
      Emitter.emit('toast', {
        message: '员工id为空，请重新登陆',
        success: () => {
          navigate('/');
        }
      });
      return;
    }
  }, [info.employee_id, navigate]);

  // 监听查询信息变化
  useEffect(() => {
    if (!info.employee_id) return;
    const getList = async () => {
      const res: ResType = await ApiCustomerList(info);
      const { code, data } = res;
      if (code === 200) {
        let _list = data?.list || [];
        let _total = data?.total || 0;
        setList(_list);
        setTotal(_total);
      }
    };
    getList();
  }, [info])

  // 设置列表
  function setListDom() {
    return (<>
      <div className='list-header'>
        <div className='item'>微信</div>
        <div className='item'>姓名</div>
        <div className='item'>手机号</div>
      </div>
      {list && list.length ? (
        list.map((item, index) => (
          <div className='list-row' key={`customer-list-${index}`}>
            <div className='item'>
              {item["wechat"]}
            </div>
          </div>
        ))
      ) : (
        <div className='list-prompt'>暂无数据</div>
      )}
    </>)
  };

  // 切换页码
  const changePage = (num: number) => {
    let _info: CustomerListType = {
      ...info,
      page: Number(num) || 1
    };
    console.log('切换页码', _info)
    setInfo(_info);
  };

  // 切换每页显示的条数
  function changePageSize(item: any) {
    console.log('每页显示的条数', item)
    if (Object.keys(item)) {
      let _info: CustomerListType = {
        ...info,
        ...{
          page: 1,
          pageSize: Number(item.value) || 10,
        }
      };
      setInfo(_info);
    }
  }

  return (
    <Layout>
      <nav className='nav'>
        <Button text='新增' handle={() => popupFunction()} />
      </nav>
      {/* 列表 */}
      {setListDom()}
      {/* 分页 */}
      {list && list?.length ? (
        <Pagination
          page={info.page}
          pageSize={info.pageSize}
          total={total}
          changePageFunction={changePage}
          changeSizeFunction={changePageSize}
        />
      ) : <></>}
      {/* 新增弹框 */}
      <Popup
        visible={popupShow}
        onChange={() => popupFunction()}
      >
        <CustomerAdd />
      </Popup>
    </Layout>
  );
}

export default Customer;
